package models

import (
	//"fmt"
	"strings"
)

type AdminMenu struct {
	Id int
	CreatedAt int
	App string
	Controller string
	Action string
	Name string
	Icon string
	Target string
	Url string
	Sorting int
	Type int
	Status int
	Parent int
	Items []*AdminMenu
}

// 取得树形结构的菜单
func GetTree(id int, parent int, level int) []*AdminMenu {
	datas, err := adminMenu(id)
	if err != nil {
		//return
		panic(err)
	}
	level++

	menus := []*AdminMenu{}
	for _, data := range datas {
		childs := GetTree(data.Id, data.Id, level)
		nodes := &AdminMenu {
			Id : data.Id,
            CreatedAt : data.CreatedAt,
            App : data.App,
            Controller : data.Controller,
            Action : data.Action,
            Name : data.Name,
			Icon : data.Icon,
			Target : data.Target,
			Url : strings.ToLower(data.App + "/" + data.Controller + "/" + data.Action),
			Sorting : data.Sorting,
			Type : data.Type,
			Status : data.Status,
			Parent : parent,
		}

		if level <= 5 {
			nodes.Items = childs
		}

		menus = append(menus, nodes)
	}

	return menus
}

func adminMenu(parentId int) (menus []AdminMenu, err error) {
	//DB.Table("admin_menu").Select("id", "name").Where("type <> ?", 3).Scan(&menus)
	//DB.Raw("SELECT * FROM admin_menu").Find(&menus)
	//DB.Raw("SELECT id, created_at, app, controller, action, name, icon, target, sorting, type, status FROM admin_menu WHERE status = 1 AND `type` <> 3 AND parent_id = ? ORDER BY sorting ASC", parentId).Scan(&menus)
	//row := DB.Table("admin_menu").Where("status = 1 AND `type` <> 3 AND parent_id = ?", parentId).Select("id", "name").Row()
	//row.Scan(&id, &name)

	// 原生 SQL
	rows, err := DB.Raw("SELECT id, created_at, app, controller, action, name, icon, target, sorting, type, status FROM admin_menu WHERE status = 1 AND `type` <> 3 AND parent_id = ? ORDER BY sorting ASC", parentId).Rows()
	defer rows.Close()
	for rows.Next() {
		conv := AdminMenu{}
		rows.Scan(&conv.Id, &conv.CreatedAt, &conv.App, &conv.Controller, &conv.Action, &conv.Name, &conv.Icon, &conv.Target, &conv.Sorting, &conv.Type, &conv.Status)
		menus = append(menus, conv)
	}

	return
}
